package com.wphmoon.pinyin.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.stuxuhai.jpinyin.ChineseHelper;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;

@Controller
@RequestMapping("/pinyin")
public class PinyinController {
	
	@RequestMapping("/")
	public String index(ModelMap map) {
		System.out.println("into index");
		return "pinyin";
	}
	
	@RequestMapping("/getPinyinHtml")
	@ResponseBody
	public String getPinyinHtml(String str) {
		return pinyinHtml(str);
	}
	
	/**把汉字（可混杂其他字符）转换成汉字拼音的html代码片段
	 * @param str
	 * @return
	 */
	private String pinyinHtml(String str) {
		String py = PinyinHelper.convertToPinyinString(str, "|", PinyinFormat.WITH_TONE_MARK);
		char[] charArray = str.toCharArray();
		String[] pyArray = py.split("\\|");
		String returnStr = "";
		int j = 0;
		for(int i=0;i<pyArray.length;i++) {
			if(ChineseHelper.isChinese(charArray[j])) {
				returnStr+="<ruby>"+charArray[j]+"<rt>"+pyArray[i]+"</rt></ruby>";
				j++;
			}else {
				for(int k=j;k<charArray.length;k++) {
					if(ChineseHelper.isChinese(charArray[j])){
						break;
					}
					returnStr +=charArray[k];
					j++;
				}
			}
		}
		return returnStr;
	}

}
